using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;

namespace WebForms.ControlExtender
{
    [ControlBuilder(typeof (TargetControlPropertiesControlBuilder)), TypeConverter(typeof (ExpandableObjectConverter))]
    public abstract class TargetControlProperties : IStateManager
    {
        private bool _isTrackingViewState;
        private StateBag _viewState;

        [NotifyParentProperty(true)]
        public String ControlId
        {
            get
            {
                object savedState = (ViewState["__ControlId"]);
                return (savedState == null) ? String.Empty : savedState.ToString();
            }
            set { ViewState["__ControlId"] = value; }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        protected StateBag ViewState
        {
            get
            {
                if (_viewState == null)
                {
                    _viewState = new StateBag(false);
                    if (_isTrackingViewState) ((IStateManager) _viewState).TrackViewState();
                }
                return _viewState;
            }
        }

        internal void SetDirty()
        {
            if (_viewState == null)
                return;

            ICollection keys = _viewState.Keys;
            if (keys != null)
                foreach (string key in keys)
                {
                    _viewState.SetItemDirty(key, true);
                }
        }

        #region IStatemanager implementation

        bool IStateManager.IsTrackingViewState
        {
            get { return _isTrackingViewState; }
        }

        void IStateManager.LoadViewState(object savedState)
        {
            if (savedState != null)
            {
                ((IStateManager) ViewState).LoadViewState(savedState);
            }
        }

        object IStateManager.SaveViewState()
        {
            return _viewState != null ? ((IStateManager) _viewState).SaveViewState() : null;
        }

        void IStateManager.TrackViewState()
        {
            _isTrackingViewState = true;
            if (_viewState != null)
                ((IStateManager) _viewState).TrackViewState();
            
        }

        #endregion
    }
}